package com.valeandre.euroro;

import com.valeandre.euroro.model.XmlGold;
import com.valeandre.euroro.net.NetworkService;
import com.valeandre.euroro.net.NetworkServiceListener;

import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;

public class MainActivity extends Activity {
	
	public final static String EXTRA_MESSAGE = "com.valeandre.euroro.value";
	public XmlGold mxmlgold;
	public double mconversion;
	Handler mHandler= new Handler();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
    
    /** Called when the user clicks the Send button */
    public void GoldConversion(View view) {
    	EditText editText = (EditText) findViewById(R.id.edit_message);
    	String valuta = editText.getText().toString();
        getConversion(valuta);
//    	Intent intent = new Intent(this, DisplayConversionActivity.class);
//    	
//    	Double value=0.0; //get the response of the feed
//    	intent.putExtra(EXTRA_MESSAGE, value);
//    	startActivity(intent);
    }
    
    
    
    public void getConversion(final String valuta) {
		Log.d("OMINO", "getConversion");
	
		NetworkService.getInstance().goldConversion(new NetworkServiceListener() {

			@Override
			public void goldConversionPerformed(XmlGold xml) {
				Log.d("OMINO", "getSettingsPerformed");
				mxmlgold=xml;
				mHandler.post(new Runnable() {

					public void run() {
						showConversion(valuta);

					}
				});
			
			}

			@Override
			public void goldConversionFailed(int statusCode) {
				Log.e("OMINO", "getSettingsFailed " + statusCode);
//				showConnectionAlertDialogAsync();
			}

			@Override
			public void goldConversionFailed(Exception e) {
				Log.e("OMINO", "getSettingsFailed " + e.getMessage());
//				showConnectionAlertDialogAsync();
			}
		});

	}
    
    
    public void showConversion(String valuta){
    	
    	for(int i=0; i<mxmlgold.getPriceList().size();i++){
    		if(mxmlgold.getPriceList().get(i).getCurrency().equalsIgnoreCase(valuta)){
    			for (int j=0; j<mxmlgold.getPriceList().get(i).getPrice().size();j++){
    				if(mxmlgold.getPriceList().get(i).getPrice().get(j).getCommodity().equalsIgnoreCase("gold")){
    					mconversion=mxmlgold.getPriceList().get(i).getPrice().get(j).getValue();
    				}
    			}
    		}
    	}
    	
    	EditText conversion = (EditText) findViewById(R.id.conversion_value);
    	CharSequence c= String.valueOf(mconversion);
    	conversion.setText(c);
    }
    
}
